package com.bdqn;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class ShortAnswer3_del {
    public static void main(String[] args) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse("src/main/java/com/bdqn/Student.xml");

            // 找到student元素节点
            NodeList student = document.getElementsByTagName("student");
            // 循环判断找出id=1的节点删除
            for (int i = 0; i < student.getLength(); i++) {
                Element element = (Element) student.item(i);
                String id = element.getAttribute("id");
                if (Integer.parseInt(id)==1)
                    element.getParentNode().removeChild(element);
            }

            // 保存XML文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);
            // 设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            StreamResult result = new StreamResult(new FileOutputStream("src/main/java/com/bdqn/Student.xml"));
            // 把DOM树转换为XML文件
            transformer.transform(domSource,result);
            System.out.println("删除成功");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

}
